package com.cn.wangxin.interceptor;

import com.cn.wangxin.annotation.AccessRequired;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述 访问权限拦截器
 *
 * @Created Time 2016/9/20
 * @Edited Time 2016/9/20
 * @Created by wangxin43
 */
public class AdminPrivilegeInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        AccessRequired annotation = method.getAnnotation(AccessRequired.class);
        if (annotation != null) {
            String token = request.getHeader("token");
            String username = request.getHeader("username");
            if("111".equals(token)){
                return true;
            }else{
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code",400);
                ObjectMapper objectMapper = new ObjectMapper();
                String result = objectMapper.writeValueAsString(map);
                response.getWriter().print(result);
                return false;
            }
        }
        return true;
    }
}

